package cn.claim.storage.tools;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Objects;

/**
 * Created by claim on 17-7-7.
 */

public final class FileAccepter {
    private final File target;
    private final Socket source;
    public final TransportingLogger logger;

    public FileAccepter(File target, Socket source) {
        this.target = target;
        this.source = source;
        this.logger = new JSONTransportingLogger(target);
    }

    /**
     * Transport a part of a file. The part size is {@code 1024 * bufferSize}.
     *
     * @return A int value means:
     * Greater than 0 - the file transporting is done.
     * Equals to 0 - the file transporting may not finish.
     * Less than 0 - the file transporting is interrupted.
     */
    public int accept(long offset) {
        int maxLength = 1024;
        InputStream input;
        RandomAccessFile output = null;
        try {
            input = source.getInputStream();
            if (!target.exists())
                target.createNewFile();
            output = new RandomAccessFile(target, "rws");
            byte[] buffer = new byte[Integer.parseInt(Config.getProp("bufferSize", "1024"))];
            int length;
            output.seek(offset);
            while (maxLength > 0 && (length = input.read(buffer)) > 0) {
                output.write(buffer, 0, length);
                maxLength--;
            }
            output.close();
            logger.log(logger.getData().getMd5(), target.length());
            return maxLength;
        } catch (IOException e) {
            try {
                if (output != null) {
                    output.close();
                }
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        }
        return -1;
    }

//    public static void main(String[] args) {
//        ServerSocket socket = null;
//        try {
//            socket = new ServerSocket(5555);
//            File accepted = new File("./README.accepted.md");
//            FileAccepter accepter = new FileAccepter(accepted, socket.accept());
//            accepter.accept(4 * 1024);
//        } catch (IOException e) {
//            e.printStackTrace();
//        } finally {
//            try {
//                if (socket != null) {
//                    socket.close();
//                }
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//    }
}
